package com.cskaoyan.controller;

import com.cskaoyan.bo.LoginBO;
import com.cskaoyan.realm.MallToken;
import com.cskaoyan.service.AuthService;
import com.cskaoyan.utils.Md5Util;
import com.cskaoyan.vo.BaseRespVo;
import com.cskaoyan.vo.InfoVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@RestController
public class AuthController {

    @Autowired
    AuthService authService;

    @PostMapping("/admin/auth/login")
    public BaseRespVo login(@RequestBody @Valid LoginBO data) throws NoSuchAlgorithmException {
        String username = data.getUsername();
        String password = data.getPassword();

        String md5Password = Md5Util.getMd5(password);

        Subject subject = SecurityUtils.getSubject();
        MallToken mallToken = new MallToken(username, md5Password, "admin");
        try {
            subject.login(mallToken);
        } catch (AuthenticationException e) {
            return BaseRespVo.fail("用户名或密码不正确", 605);
        }

        // 到这里则认证成功, 更新登录信息
        String host = subject.getSession().getHost();
        Date lastAccessTime = subject.getSession().getLastAccessTime();
        authService.updateHostAndLoginTime(host, lastAccessTime, username);

        Session session = subject.getSession();
        session.setAttribute("username", username);
        Serializable sessionId = session.getId();
        return BaseRespVo.ok(sessionId);
    }

    @GetMapping("/admin/auth/info")
    public BaseRespVo info(String token) {
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getSession().getAttribute("username");
        InfoVO infoVO = authService.queryByUsername(username);
        return BaseRespVo.ok(infoVO);
    }

    @PostMapping("/admin/auth/logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

    @RequestMapping("/401")
    public BaseRespVo unauthc() {
        return BaseRespVo.fail("请先登录", 501);
    }
}
